package com.loser.gateway.mq.consumer;

import com.loser.gateway.broadcast.BroadCastHandler;
import com.loser.module.base.mq.gateway.GateWayConst;
import com.loser.module.base.proto.broadcast.BroadCastMsg;
import com.loser.utils.trace.MDCUtil;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Slf4j
@Component
public class BroadCastMsgConsumer {

    @Autowired
    private BroadCastHandler broadCastHandler;

    @RabbitListener(
            // 绑定队列
            bindings = {
                    // 绑定队列的类
                    @QueueBinding(
                            // 1.队列名称
                            value = @Queue(),
                            // 消息交换器 1.交换器名称，2.交换器类型
                            exchange = @Exchange(value = GateWayConst.BroadCast.exchange, type = ExchangeTypes.FANOUT))
            }, concurrency = "20")
    public void receiver(@Payload BroadCastMsg msg, @Headers Map<String, Object> headers, Channel channel) throws IOException {

        long deliveryTag = (long) headers.get(AmqpHeaders.DELIVERY_TAG);
        try {
            MDCUtil.setTraceId(msg.getTraceId());
            log.info("BroadCastMsgConsumer data {}", msg);
            broadCastHandler.sendBroadCast(msg);
        } catch (Exception e) {
            log.error("BroadCastMsgConsumer throw an error data {}", msg, e);
        } finally {
            // mq消息ack
            channel.basicAck(deliveryTag, false);
            MDCUtil.removeTraceId();
        }

    }

}
